<?php

class InvoiceDocController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/customer';

	/**
	 * @return array action filters
	 */

	public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions

               'users'=>array('@'),
            ),

            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate($invoice)
	{

         $invoice = Invoice::model()->findByPk($invoice);
         $location=Locations::model()->find('locno=:locno',
                                             array('locno'=>$invoice->locno));
         $customer = Customers::model()->find('custno=:custno',array(
                    'custno'=>$location->custno));
         $model = new Documents();
         $model->notes = $invoice->invoice;
         $model->addedby = Yii::app()->user->name;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Documents']))
		{
			$model->attributes=$_POST['Documents'];
			if($model->save())
				$this->redirect(array('index','invoice'=>$model->notes));
		}

		$this->render('create',array('location'=>$location,
                                          'customer'=>$customer,
                                          'model'=>$model));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
          $invoice = Invoice::model()->findByPk($model->notes);
         $location=Locations::model()->find('locno=:locno',
                                             array('locno'=>$invoice->locno));
         $customer = Customers::model()->find('custno=:custno',array(
                    'custno'=>$location->custno));
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Documents']))
		{
			$model->attributes=$_POST['Documents'];
			if($model->save())
				$this->redirect(array('index','invoice'=> $invoice->invoice));
		}

	    $this->render('update',array('location'=>$location,
                                          'customer'=>$customer,
                                          'model'=>$model));
	}

	/**
	 * Deletes a particular model
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{

			$model=$this->loadModel($id);
            $invoice = $model->notes;
            $model->delete();
			$this->redirect(array('index','invoice'=>$invoice));

	}

	/**
	 * Lists all models.
	 */
	public function actionIndex($invoice){

        $model = Invoice::model()->findByPk($invoice);
        $location=Locations::model()->find('locno=:locno',
                            array('locno'=>$model->locno));
        $customer = Customers::model()->find('custno=:custno',array(
                                       'custno'=>$location->custno));
         $this->render('index',array('location'=>$location,
                                             'customer'=>$customer,
                                             'model'=>$model));


	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new InvoiceEmp('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Documents']))
			$model->attributes=$_GET['Documents'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Documents::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
     //TODO move this code to model
    public function actionGetInvoiceDoc($invoice,$page=1, $sort=NULL, $dir=NULL) {
        //we decrease $page by 1 because in Extjs first page is 1, but in our sql first page is 0;
        if ($page > 0)
            $page--;

        $employers = new CActiveDataProvider('Documents', array(
                    'criteria' => array(
                        'condition'=>"notes='$invoice'",
                        'order' => $sort != NULL ? $sort . ' ' . $dir : '',
                    ),
                    'pagination' => array(
                        'pageSize' => 20,
                        'currentPage' => $page,
                    ),
                ));

        $empList = array();
        if ($employers->getTotalItemCount() > 0) {
            $empList['totalCount'] =  $employers->getTotalItemCount();
            $empList['type'] = 'Items';
            foreach ( $employers->getData() as $item) {
                $empList['data'][] = $item->getAttributes();
            }
            echo json_encode($empList);
        }
        Yii::app()->end();
    }


	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='documents-emp-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
